<template>
  <!-- 在子组件发送的时候以addTodo命名,这里用的时候使用横杠的方式调用 -->
  <TodoHeader @add-todo="handleAddTodo"></TodoHeader>
  <TodoList>
    <!-- item-key绑定的id就是todos里面的id,并且必须要使用一个插槽模版 -->
    <draggable v-model="todos" item-key="id">
      <!-- 模版中不能写注释,相当于v-for渲染 -->
      <template #item="{element}">
        <TodoItem  v-bind="element" @toggle="handleChange" @edit="handleEdit" @delete="handleDelete"></TodoItem>
      </template>
    </draggable>
    <!-- v-bind等同于绑定所有的数据 -->
    <!-- <TodoItem v-for="(todo ,index) in todos" :key="todo.id" :id="todo.id" :content="todo.content" :done="todo.done"></TodoItem> -->
  </TodoList>
  <TodoFooter :todos="todos" @clear-done="handleClearDone" @clear-all="handleClearAll" @toggle-all="handleToggleAll"></TodoFooter>
</template>

<script setup>
import TodoHeader from './components/TodoHeader.vue';
import TodoList from './components/TodoList.vue';
import TodoFooter from './components/TodoFooter.vue';
import TodoItem from './components/TodoItem.vue';
import {ref,onMounted,watch} from 'vue'
import draggable from 'vuedraggable'
//定义一个数组接收数据
const todos = ref([])
//添加数据
const handleAddTodo = (todo)=>{
  todos.value.push(todo)
}
//input输入框状态修改
const handleChange = (id,value)=>{
  todos.value.find(todo=>todo.id === id).done = value
}
//input输入框值修改
const handleEdit =(id,value)=>{
  todos.value.find(todo=>todo.id ===id).content = value
}
//删除数据
const handleDelete = (id)=>{
  //方法1
  //todos.value = todos.value.filter(todo=>todo.id !== id)
  //方法2
  const index = todos.value.findIndex(todo =>todo.id ===id)
   todos.value.splice(index,1)
}
//清除已办
const handleClearDone = ()=>{
  todos.value = todos.value.filter(todo =>!todo.done)
}
//清除所有
const handleClearAll = ()=>{
  todos.value =[]
}
//切换全选/取消全选
const handleToggleAll = (value)=>{
  todos.value.forEach((todo)=>todo.done = value)
}
//实现数据持久化
onMounted(()=>{
  //从localStorage中获取数据
  //从浏览器(localStorage中获取todos数据),如果有转为字符串然后赋值给localTodos,如果没有返回[]
  const localTodos = JSON.parse(localStorage.getItem('todos') || '[]')
  todos.value = localTodos
})
watch(todos,()=>{
  //存储数据到localStorage
  //将todos数据转为字符串,存储到浏览器中,键值名为todos
  localStorage.setItem('todos',JSON.stringify(todos.value))
},
{deep:true})
</script>

<style>
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}


</style>